package com.reading.message.service.impl;

import com.reading.common.cache.service.CacheService;
import com.reading.common.utils.StringUtil;
import com.reading.message.config.EmailConfig;
import com.reading.message.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author guwenqi_1995@163.com
 * @date 2019/7/8 9:43 AM
 **/
@Slf4j
@Service
public class EmailServiceImpl implements EmailService {

    @Resource
    private JavaMailSender sender;

    @Resource
    private CacheService cacheService;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendAuthCode(String to) {
        //获取验证码
        String validationCode = StringUtil.getRandomString(EmailConfig.EMAIL_VALIDATOR_CODE_LENGTH);
        //发送邮件
        sendEmail(to, validationCode);
        //保存到缓存中
        cacheService.setEmailCode(to, validationCode);
    }

    private void sendEmail(String to, String validationCode) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(to);
        mailMessage.setSubject(EmailConfig.SUBJECT);
        mailMessage.setText(String.format(EmailConfig.TEXT, validationCode));
        sender.send(mailMessage);
    }
}
